<script lang="ts" setup>
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'
import type { TableBorder, TableData, TableSortable } from '@arco-design/web-vue'
import { Workbook } from 'exceljs'
import { Notification } from '@arco-design/web-vue'
import { IconSearch } from '@arco-design/web-vue/es/icon'
import { ReportApi } from '@/apis'
import { useTable } from '@/hooks/modules/useTable'
import { useForm } from '@/hooks'
import { generateHeaders, saveWorkbook } from '@/utils/excel'
import type { TableInstanceColumns } from '@/components/ProTable/type'

defineOptions({
  name: 'TeacherLessonReport',
})

const { form } = useForm<ReportApi.TeacherLessonReportQuery>({
  month: dayjs().format('YYYY-MM'),
  teacherType: 'LEAD_TEACHER',
})

const maxLessonCount = ref(0)
const {
  tableData,
  loading,
  search,
} = useTable(() => ReportApi.getTeacherLessonReport(form), {
  onSuccess: async () => {
    maxLessonCount.value = 0
    tableData.value.forEach((item) => {
      if (item.lessonCount > maxLessonCount.value) {
        maxLessonCount.value = item.lessonCount
      }
    })
    tableData.value.forEach((item) => {
      for (let index = 0; index < maxLessonCount.value; index++) {
        item[`signInDetails${index}`] = item.signInDetails.length > index ? item.signInDetails[index] : undefined
      }
    })
  },
})

const border: TableBorder = {
  wrapper: true,
  cell: true,
  headerCell: true,
  bodyCell: true,
}
// 筛选
const onFilterChange = (dataIndex, filteredValues) => {
  form[dataIndex] = filteredValues
}

const nameSortable: TableSortable = {
  sortDirections: ['ascend', 'descend'],
  defaultSortOrder: 'ascend',
  sorter: (a: TableData, b: TableData, extra: { dataIndex: string, direction: 'ascend' | 'descend' }) => {
    if (extra.direction === 'ascend') {
      return a.teacherName.localeCompare(b.teacherName, 'zh-Hans-CN', { sensitivity: 'accent' })
    } else {
      return b.teacherName.localeCompare(a.teacherName, 'zh-Hans-CN', { sensitivity: 'accent' })
    }
  },
}

const sortable: TableSortable = {
  sortDirections: ['ascend', 'descend'],
  // sortOrder: 'ascend',
}

const filterable = {
  filter: (value, record) => record.teacherName.includes(value),
  slotName: 'name-filter',
  icon: () => h(IconSearch),
}
// 重新计算
const computeLoading = ref(false)
const onComputeReport = () => {
  computeLoading.value = true
  ReportApi.computeTeacherLessonReport(form).then((res) => {
    Notification.success({
      title: '温馨提示',
      content: '数据计算完毕！',
    })
    search()
  }).finally(() => {
    computeLoading.value = false
  })
}

const onExportExcel = () => {
  const workbook = new Workbook()
  const worksheet = workbook.addWorksheet('课时信息')
  worksheet.properties.defaultRowHeight = 20
  const childrenColumns: TableInstanceColumns[] = []
  for (let index = 0; index < maxLessonCount.value; index++) {
    childrenColumns.push({ title: `第${index + 1}节课`, dataIndex: `signInDetails${index}`, width: 100 })
  }
  const columns: TableInstanceColumns[] = [
    { title: '老师', dataIndex: 'teacherName', width: 88 },
    { title: '班级', dataIndex: 'className', width: 360 },
    { title: '本月课次', dataIndex: 'lessonCount', width: 100 },
    { title: '课时业绩系数', dataIndex: 'lessonHourFactor', width: 120 },
    { title: '签到情况', children: childrenColumns },
    { title: '签到总人数', dataIndex: 'signInCount', width: 120 },
    { title: '满班总人次', dataIndex: 'fullClassCount', width: 120 },
    { title: '课时费系数', dataIndex: 'lessonPriceFactor', width: 120 },
    { title: '备注', dataIndex: 'remark', width: 120 },
  ]
  worksheet.columns = generateHeaders(columns)
  const data = tableData.value.map((item) => {
    return {
      ...item,
    }
  })
  worksheet.addRows(data)
  saveWorkbook(workbook, `课时统计_${form.month}.xlsx`)
}

const debouncedSearch = useDebounceFn(() => search(), 100)

watch(() => form, () => debouncedSearch(), { deep: true })
</script>

<template>
  <ProPage title="教师课时统计" description="教师课时统计数据为非实时，按月汇总统计，每月2号凌晨自动更新计算上月数据">
    <template #extra>
      <a-space>
        <a-button type="text" :loading="computeLoading" @click="onComputeReport">
          重新计算
        </a-button>
        <a-button type="primary" @click="onExportExcel">
          导出
        </a-button>
      </a-space>
    </template>
    <a-alert class="mb" title="课时费系数计算规则">
      所有班级合并计算
      <a-tooltip>
        <span class="tooltip-item">课时费系数</span>
        <template #content>
          满班率和课时费系数换算规则：<br>
          1. 满班率≥120%,取1.15;<br>
          2. 110%≤满班率&lt;120%,取1.1;<br>
          3. 100%≤满班率&lt;110%,取1.05;<br>
          4. 75%≤满班率&lt;100%,取1;<br>
          5. 60%≤满班率&lt;75%,取0.9;<br>
          6. 45%≤满班率&lt;60%,取0.7;<br>
          7. 满班率&lt;45%,取0.5。<br>
        </template>
      </a-tooltip>
      为X，普通班单独计算课时费系数为Y，
      <a-tooltip>
        <span class="tooltip-item">高端班</span>
        <template #content>
          高端班：权限等级≥600的小学思维课；<br>
          普通班：高端班之外的其它班级。
        </template>
      </a-tooltip>单独计算课时费系数为Z。<br>
      ①若只有高端班，则课时费系数为max(1.0, Z);<br>
      ②若X≥Y，则所有班级课时费系数都为X;<br>
      ③若X&lt;Y，普通班课时费系数为Y，高端班课时费系数为max(1.0, Z)。
    </a-alert>
    <a-space class="mb">
      <a-month-picker v-model="form.month" class="w-200px" />
      <a-radio-group v-model="form.teacherType" type="button">
        <a-radio value="LEAD_TEACHER">
          主讲老师
        </a-radio>
        <a-radio value="ASSIST_TEACHER">
          辅导老师
        </a-radio>
      </a-radio-group>
    </a-space>
    <a-table
      row-key="id"
      :stripe="false"
      :data="tableData"
      :loading="loading"
      size="medium"
      :scroll="{ x: '100%', y: '100%', minWidth: 960 }"
      column-resizable
      :bordered="border"
      :pagination="false"
      :filter-icon-align-left="false"
    >
      <template #columns>
        <a-table-column data-index="id" title="#" :width="66" fixed="left">
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column data-index="teacherName" title="老师" align="center" fixed="left" :width="120" :sortable="nameSortable" :filterable="filterable" />
        <a-table-column data-index="className" title="班级" :width="360" align="center" fixed="left" :tooltip="true" :ellipsis="true" />
        <a-table-column data-index="lessonCount" title="本月课次" align="right" :width="100" />
        <a-table-column data-index="lessonHourFactor" title="课时业绩系数" align="right" :width="120">
          <template #cell="{ record }">
            {{ record.lessonHourFactor.toFixed(2) }}
          </template>
        </a-table-column>
        <a-table-column title="签到情况" data-index="signInDetails" align="center">
          <a-table-column v-for="(item, index) in maxLessonCount" :key="index" :title="`第${item}节`" align="right" :width="100">
            <template #cell="{ record }">
              {{ record[`signInDetails${index}`] ?? '-' }}
              <!-- {{ record.signInDetails.length > index ? record.signInDetails[index] : '-' }} -->
            </template>
          </a-table-column>
        </a-table-column>
        <a-table-column data-index="signInCount" align="right" title="签到总人数" :width="130" :sortable="sortable" />
        <a-table-column data-index="fullClassCount" align="right" title="满班总人次" :width="120" />
        <a-table-column data-index="lessonPriceFactor" align="right" title="课时费系数" :width="120">
          <template #cell="{ record }">
            {{ record.lessonPriceFactor.toFixed(2) }}
          </template>
        </a-table-column>
        <a-table-column data-index="remark" title="备注" align="center" :min-width="100">
          <template #cell="{ record }">
            {{ record.remark || '-' }}
          </template>
        </a-table-column>
      </template>
      <template #name-filter="{ filterValue, setFilterValue, handleFilterConfirm, handleFilterReset }">
        <div class="custom-filter">
          <a-space direction="vertical">
            <a-input :model-value="filterValue[0]" @input="(value) => setFilterValue([value])" />
            <div class="custom-filter-footer">
              <a-button @click="handleFilterReset">
                重置
              </a-button>
              <a-button type="primary" @click="handleFilterConfirm">
                确定
              </a-button>
            </div>
          </a-space>
        </div>
      </template>
    </a-table>
    <!-- </ProTable> -->
  </ProPage>
</template>

<style lang="less" scoped>
.custom-filter {
  padding: 20px;
  background: var(--color-bg-5);
  border: 1px solid var(--color-neutral-3);
  border-radius: var(--border-radius-medium);
  box-shadow: 0 2px 5px rgb(0 0 0 / 10%);
}

.custom-filter-footer {
  display: flex;
  justify-content: end;
  gap: 12px;
}

.tooltip-item {
  color: rgb(var(--primary-6));

  &:hover {
    cursor: pointer;
  }
}
</style>
